<?php

declare(strict_types=1);

namespace app\model;

use think\Model;
use think\model\concern\SoftDelete;

class User extends Model
{
    use SoftDelete;

    protected $name = 'user_account';

    protected $autoWriteTimestamp = 'datetime';

    protected $hidden = ['password_hash'];

    protected $append = ['user_type'];

    // 资料
    public function profile()
    {
        return $this->hasOne(UserProfile::class, 'user_id');
    }

    // 登录凭证
    public function auths()
    {
        return $this->hasMany(UserAuth::class, 'user_id');
    }

    // 业务身份
    public function identities()
    {
        return $this->hasMany(UserIdentity::class, 'user_id');
    }

    public function identitiesByType(string $type)
    {
        return $this->identities()->where('identity_type', $type);
    }

    // 个人/企业认证
    public function individual()
    {
        return $this->hasOne(UserIndividual::class, 'user_id');
    }

    public function company()
    {
        return $this->hasOne(UserCompany::class, 'user_id');
    }

    // 角色
    public function roles()
    {
        return $this->belongsToMany(AuthRole::class, 'auth_user_role', 'role_id', 'user_id');
    }

    // 组织成员
    public function orgMembers()
    {
        return $this->hasMany(OrgMember::class, 'user_id');
    }

    public function orgs()
    {
        return $this->belongsToMany(Org::class, 'org_member', 'org_id', 'user_id');
    }

    // 区域
    public function regionUsers()
    {
        return $this->hasMany(RegionUser::class, 'user_id');
    }

    public function regions()
    {
        return $this->belongsToMany(Region::class, 'region_user', 'region_id', 'user_id');
    }

    public function primaryRegion()
    {
        return $this->regionUsers()->with('region')->where('is_primary', 1)->find();
    }

    // 邀请人
    public function inviter()
    {
        return $this->belongsTo(self::class, 'invited_by');
    }

    // 权限校验
    public function hasPermission(string $code): bool
    {
        return $this->roles()
            ->whereExists(function ($query) use ($code) {
                $alias = AuthRolePerm::getTable();
                $query->name($alias)
                    ->whereColumn($alias . '.role_id', 'auth_role.id')
                    ->whereExists(function ($permQuery) use ($alias, $code) {
                        $permQuery->name(AuthPermission::getTable())
                            ->whereColumn(AuthPermission::getTable() . '.id', $alias . '.permission_id')
                            ->where('code', $code);
                    });
            })
            ->count() > 0;
    }

    public function getUserTypeAttr(): string
    {
        $identity = $this->identities()->order('status', 'desc')->order('id', 'asc')->value('identity_type');
        return $identity ?: 'guest';
    }
}
